package com.liqw.fastswing.ui.controller;

import com.liqw.fastswing.domain.entity.User;
import com.liqw.fastswing.domain.mapper.UserMapper;
import com.liqw.fastswing.service.UserService;
import com.liqw.fastswing.ui.view.MainView;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.annotation.PostConstruct;
import javax.swing.*;
import java.util.List;

/**
 * This is the main view of the application.  If it gets closed, then the application stops.
 */
@Controller
public class MainController extends JFrame {
    @Autowired
    private UserService userService;
    @Autowired
    private UserController userController;

    private final MainView mainView;

    public MainController() {
        super("用户列表");
        this.mainView = new MainView() {
            @Override
            protected void newButtonClicked() {
                addUser();
            }

            @Override
            protected void viewButtonClicked() {
                viewUser();
            }
        };

        this.setContentPane(mainView.getRootComponent());
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);

        this.pack();
    }

    @PostConstruct
    public void initData(){
        List<User> userList = userService.list();
        mainView.setUserListInfo(userList);
    }

    private void addUser() {
        userController.setModel(new User());
        userController.setVisible(true);
    }

    private void viewUser() {
        Long id = mainView.getSelected().getId();
        User user = userService.getById(id);
        userController.setModel(user);
        userController.setVisible(true);
    }

    /**
     * I hook the refresh of the JList up to the validate method.  Then you can call it from another view without
     * having to actually know the implementation under the hood.  It's just a JFrame that you're validating.
     */
    @Override
    public void validate() {
        super.validate();
    }
}
